package com.lanhao.aot.aes;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.tomcat.util.codec.binary.Base64;

public class AESUtil {
	// AES parameters
	private static final String KEY_ALGORITHM = "AES";
	private static final String CIPHER_ALGORITHM = "AES/CTR/NoPadding";
	private static final String CHARSET_NAME = "UTF-8";
	private static final String IV = "JpCZaCrmtRLJHoIs";
	private static final String AES_CTR_KEY = "yvkwTs9gUC7Y4Je2MF8GL1cGG3N1o5xR";

	public static void main(String[] args) throws Exception {

		String data = "{\"deviceSnList\":\"C4C00400FF040361016T190440DD804DBD\",\"tpAccount\":\"11111111111\",\"doorbellId\":\"11\",\"doorbellKey\":\"11\",\"src\":\"ctcc\",\"state\":1,\"doorbellToken\":\"11\",\"reqTime\":\"1578652802662\"}";

		String encryptResult = encrypt(data, AES_CTR_KEY, IV);

		System.out.println("加密结果：encryptResult =" + encryptResult);
		
		String decryptResult = decrypt(encryptResult, AES_CTR_KEY, IV);
		
		System.out.println("解密结果：decryptResult =" + decryptResult);


	}
	private static String encrypt(String data, String md5Key, String iv) {
        try {
            IvParameterSpec zeroIv = new IvParameterSpec(iv.getBytes());
            //两个参数，第一个为私钥字节数组， 第二个为加密方式 AES或者DES
            SecretKeySpec key = new SecretKeySpec(md5Key.getBytes(), KEY_ALGORITHM);
            //实例化加密类，参数为加密方式，要写全
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            //初始化，此方法可以采用三种方式，按加密算法要求来添加。（1）无第三个参数（2）第三个参数为SecureRandom random = new SecureRandom();中random对象，随机数。(AES不可采用这种方法)（3）采用此代码中的IVParameterSpec
            cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
            //加密操作,返回加密后的字节数组，然后需要编码。主要编解码方式有Base64, HEX, UUE,7bit等等。此处看服务器需要什么编码方式
            byte[] encryptedData = cipher.doFinal(data.getBytes(CHARSET_NAME));
            return Base64.encodeBase64String(encryptedData); // 用此方法不带换行符的
            
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
	
	private static String decrypt(String data, String strKey, String iv) {
		try {
			byte[] byteMi = Base64.decodeBase64(data);
			IvParameterSpec zeroIv = new IvParameterSpec(iv.getBytes());
			// 两个参数，第一个为私钥字节数组， 第二个为加密方式 AES或者DES
			SecretKeySpec key = new SecretKeySpec(strKey.getBytes(), KEY_ALGORITHM);
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
			byte[] decryptedData = cipher.doFinal(byteMi);
			return new String(decryptedData, CHARSET_NAME);
		} catch (Exception e) {
			return null;
		}
	}

}
